<template>
  <div class="orderManage-container">
    <div class="header-container">
      <el-form :model="form" label-width="100px" ref="seachRef">
        <el-row :gutter="20">
          <el-col :span="6">
            <xm-f-intput
              v-model="form.title"
              prop="orderSn"
              label="商品名称:"
            ></xm-f-intput>
          </el-col>

          <el-col :span="6">
            <xm-f-intput
              v-model="form.orderSn"
              prop="orderSn"
              label="订单编号:"
            ></xm-f-intput>
          </el-col>

          <el-col :span="6">
            <XmFSelect
              v-model="form.paymentMethod"
              prop="paymentMethod"
              label="支付方式:"
              :options="payOptions"
              multiple
            ></XmFSelect>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="创建时间:" prop="time">
              <XMDatePicker
                v-model="form.time"
                v-model:startTime="form.startTime"
                v-model:endTime="form.endTime"
                type="daterange"
                disabledDateT="after"
                label="选择开始时间:"
                style="width: 180px"
                :config="{ shortcuts: true }"
              ></XMDatePicker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="3">
            <el-button @click="loadData" type="primary" style="width: 100%">
              筛选
            </el-button>
          </el-col>
          <el-col :span="3">
            <el-button @click="clear" style="width: 100%">清空</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="content-container">
      <div class="shop-table-header">
        <el-radio-group
          v-model="form.orderStatusList"
          style="margin-bottom: 30px"
          @change="loadData"
        >
          <el-radio-button :label="null">全部</el-radio-button>
          <el-radio-button :label="[0, 1]">待付款</el-radio-button>
          <el-radio-button :label="[10]">待发货</el-radio-button>
          <el-radio-button :label="[20]">待收货</el-radio-button>
          <el-radio-button :label="[50]">已完成</el-radio-button>
          <el-radio-button :label="[65, 68]">退款中</el-radio-button>
          <el-radio-button :label="[70]">退款成功</el-radio-button>
          <el-radio-button :label="[99]">已关闭</el-radio-button>
        </el-radio-group>

        <el-radio-group
          v-model="form.asc"
          style="margin-bottom: 30px"
          @change="loadData"
        >
          <el-radio-button :label="false">下单时间由近到远</el-radio-button>
          <el-radio-button :label="true">下单时间由远到近</el-radio-button>
        </el-radio-group>
      </div>
      <PaginationTable
        ref="paginationTableRef"
        :tableData="listData"
        @pagination="paginaChange"
        :spanMethod="arraySpanMethod"
        :cellStyle="{
          'background-color': 'rgb(240, 242, 245)',
          'padding-top': '0px',
          'padding-bottom': ' 0px',
        }"
      >
        <el-table-column label="商品">
          <template #default="props">
            <div class="section-header">
              <div>
                订单号：{{ props.row.orderSn }} 下单时间：{{
                  props.row.createTime
                }}
              </div>
              <div>
                <el-button
                  text
                  type="primary"
                  @click="sectionHeader(props.row, 1)"
                >
                  查看详情
                </el-button>
                <el-button
                  text
                  type="primary"
                  @click="sectionHeader(props.row, 2)"
                >
                  复制订单
                </el-button>
                <el-button
                  v-if="[0].includes(props.row.orderStatus)"
                  text
                  type="danger"
                  @click="closeOrder(props.row)"
                >
                  关闭订单
                </el-button>
                <el-button
                  v-if="[0].includes(props.row.orderStatus)"
                  text
                  type="primary"
                  @click="modifyPrice(props.row)"
                >
                  修改价格
                </el-button>
                <el-button
                  v-if="[10, 20].includes(props.row.orderStatus)"
                  text
                  type="primary"
                  @click="deliverGoodsAction(props.row)"
                >
                  {{ props.row.orderStatus === 10 ? '发货' : '修改物流' }}
                </el-button>
                <el-button
                  v-if="[10, 20].includes(props.row.orderStatus)"
                  text
                  type="danger"
                  @click="refundOrder(props.row)"
                >
                  退款
                </el-button>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="划线价(元)/数量"></el-table-column>

        <el-table-column label="买家/收货人"></el-table-column>

        <el-table-column label="配送方式"></el-table-column>

        <el-table-column label="实收金额"></el-table-column>

        <el-table-column label="订单状态"></el-table-column>

        <!-- <el-table-column label="操作"></el-table-column> -->

        <el-table-column type="expand">
          <template #default="oneAll">
            <el-table
              :data="oneAll.row.orderDetails"
              :border="true"
              :show-header="false"
              :highlight-current-row="false"
              :span-method="subSpanMethod"
            >
              <el-table-column label="商品" prop="goodsTitle">
                <template #default="{ row }">
                  <div class="cell-img">
                    <ImageView v-model="row.images"></ImageView>
                    <div>
                      <el-popover
                        placement="top-start"
                        :width="200"
                        trigger="hover"
                        title="商品名"
                        :content="row.goodsTitle"
                      >
                        <template #reference>
                          <span class="tips">{{ row.goodsTitle }}</span>
                        </template>
                      </el-popover>
                      <div class="tips">{{ row.specValue }}</div>
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="划线价（元）/数量" prop="state">
                <template #default="props">
                  <div>
                    {{ props.row.goodsPrice / 100 + '元' }} /
                    {{ props.row.num }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="买家/收货人">
                <template #default>
                  <div>{{ oneAll.row.receiver }}</div>
                  <div>{{ oneAll.row.receiverPhone }}</div>
                  <div>
                    {{
                      oneAll.row.receiverProvince +
                      '-' +
                      oneAll.row.receiverCity +
                      '-' +
                      oneAll.row.receiverArea
                    }}
                  </div>
                </template>
              </el-table-column>

              <el-table-column label="配送方式">
                <template #default>快递配送</template>
              </el-table-column>
              <el-table-column label="实收金额">
                <template #default>
                  {{
                    (oneAll.row.orderAmount +
                      oneAll.row.freightAmount +
                      oneAll.row.variableAmount) /
                    100
                  }}元
                </template>
              </el-table-column>
              <el-table-column label="订单状态">
                <template #default>
                  <div>{{ renderStatus(oneAll.row.orderStatus) }}</div>
                  <div>{{ renderStatusToClose(oneAll.row) }}</div>
                </template>
              </el-table-column>
              <!-- <el-table-column label="操作" prop="zip">
                <template #default="{ row }">
                  <el-button
                    v-if="[0].includes(oneAll.row.orderStatus)"
                    size="small"
                    type="danger"
                    @click="closeOrder(oneAll.row)"
                  >
                    关闭订单
                  </el-button>
                  <el-button
                    v-if="[0].includes(oneAll.row.orderStatus)"
                    size="small"
                    type="primary"
                    @click="modifyPrice(oneAll.row)"
                  >
                    修改价格
                  </el-button>
                  <el-button
                    v-if="[10, 20].includes(oneAll.row.orderStatus)"
                    size="small"
                    type="primary"
                    @click="deliverGoodsAction(oneAll.row)"
                  >
                    {{ row.status === 10 ? '发货' : '修改物流' }}
                  </el-button>
                  <el-button
                    v-if="[10, 20].includes(oneAll.row.orderStatus)"
                    size="small"
                    type="danger"
                    @click="refundOrder(oneAll.row)"
                  >
                    退款
                  </el-button>
                </template>
              </el-table-column> -->
            </el-table>
          </template>
        </el-table-column>
      </PaginationTable>
    </div>
    <!-- 修改价格 -->
    <!--    <batch-price-change-comp-->
    <!--      :dia-log-visible="batchPriceShow"-->
    <!--      :selItems="selArrays"-->
    <!--      @addSuccess="loadData"-->
    <!--    ></batch-price-change-comp>-->
    <modifyPriceDialog
      v-model:modifyPriceDialog="batchPriceShow"
      :id="selArrays.id"
      :orderData="selArrays"
      @addSuccess="
        () => {
          selArrays.value = {}
          loadData()
        }
      "
    ></modifyPriceDialog>
    <!-- 发货 -->
    <deliverGoodsDialog
      v-model:dialogVisible="deliverGoods"
      :orderData="selArrays"
      @addSuccess="
        () => {
          selArrays.value = {}
          loadData()
        }
      "
    ></deliverGoodsDialog>
  </div>
</template>
<script lang="ts" setup>
  import { useRouter } from 'vue-router'
  import { reactive, ref, computed } from 'vue'
  import { Top, Bottom, Download } from '@element-plus/icons-vue'
  import { getOrderList } from '@/api/modules/shop'
  import type { unsaleableType } from '@/api/modules/shop'
  import { onMountedOrActivated } from '@/hooks/core/onMountedOrActivated'
  import ImageView from '@/components/ImageView/index.vue'
  import { usePromise } from '@/hooks/core/usePromise.js'
  import common, { XmCopy } from '@/utils/common'
  import modifyPriceDialog from '../../components/modifyPriceDialog/index.vue'
  // eslint-disable-next-line max-len
  import batchPriceChangeComp from '../../components/batchPriceChangeComp/index.vue'
  import deliverGoodsDialog from '../../components/deliverGoodsDialog/index.vue'

  import { useOrder } from '../../hooks/useOrder'
  import router from '@/router'
  import { useStore } from 'vuex'

  const store = useStore()
  const form = ref(initFrom())
  onMountedOrActivated(() => {
    loadData()
    if (!store.getters.expressTypes || store.getters.expressTypes.length <= 0) {
      store.dispatch('shop/setExpressTypes')
    }
  })

  const { to } = usePromise()
  const listData = ref({})
  async function loadData() {
    common.XmLoading(true)
    const [err, res] = await to(getOrderList(form.value))
    common.XmLoading()
    if (!err) {
      listData.value = res
      // @ts-ignore：无法被执行的代码的错误
      listData.value.data = res.data.map((item: any) => {
        const { orderDetails } = item
        item.orderDetails = orderDetails.map((element: any) => {
          element.images = [{ url: element.goodsImage }]

          if (Array.isArray(element.goodsSpecValues)) {
            element.specValue = '规格: ' + element.goodsSpecValues.join('&')
          } else {
            element.specValue = '单规格'
          }
          return element
        })
        return item
      })
    }
  }

  const payOptions = [
    { label: '微信支付', value: 2 },
    { label: '未付款', value: 0 },
  ]

  function initFrom() {
    return {
      orderSn: null,
      orderStatus: null,
      orderStatusList: null,
      paymentMethod: null,
      time: null,
      startTime: null,
      endTime: null,
      asc: false,
      pageIndex: 1,
      pageSize: 5,
      title: null,
    }
  }

  // target-action
  const paginationTableRef = ref()
  function paginaChange(params: any) {
    form.value.pageIndex = params.current
    form.value.pageSize = params.pageSize
    loadData()
  }

  function clear() {
    form.value = initFrom()
    paginationTableRef.value.clearData()
    loadData()
  }

  function sectionHeader(row: any, type: number) {
    const { id } = row
    if (type === 1) {
      // 查看详情
      router.push({
        path: 'OrderDetails',
        query: { id },
      })
    } else {
      // 复制
      const b = common.XmCopy(row.orderSn)
      common.XmMessage(0, b ? '复制成功' : '复制失败')
    }
  }

  const { refund, closeOrderWithId, orderStatusWithLabel } = useOrder()
  const renderStatus = computed(
    () => (val: number) => orderStatusWithLabel(val)
  )
  const renderStatusToClose = computed(() => (item: any) => {
    const { orderStatus, closeOrderType } = item
    if (orderStatus === 99) {
      if (closeOrderType === 0) {
        return '超时系统自动关闭'
      } else if (closeOrderType === 1) {
        return '买家自动关闭'
      } else if (closeOrderType === 2) {
        return '卖家自动关闭'
      } else {
        return ''
      }
    } else {
      return ''
    }
  })
  // const { to } = usePromise()
  // 关闭订单
  async function closeOrder(row: any) {
    const [err, res] = await to(closeOrderWithId(row.id))
    if (!err) loadData()
  }
  // 修改价格
  const batchPriceShow = ref(false)
  const selArrays = ref([])
  function modifyPrice(row: any) {
    console.log('row =' + JSON.stringify(row))
    batchPriceShow.value = !batchPriceShow.value
    selArrays.value = row
  }

  // 发货
  const deliverGoods = ref(false)
  const orderWithExpressId = ref()
  function deliverGoodsAction(row: any) {
    console.log('row =' + JSON.stringify(row))
    deliverGoods.value = !deliverGoods.value
    selArrays.value = row
  }

  // 退款
  async function refundOrder(row: any) {
    const [err, res] = await to(refund(row.id))
    if (!err) loadData()
  }

  // 合并section header
  function arraySpanMethod(data: any) {
    const { row, column, rowIndex, columnIndex } = data
    if (columnIndex === 0) {
      return [1, 8]
    }
  }
  // 合并子列表
  function subSpanMethod(data: any) {
    const { row, column, rowIndex, columnIndex } = data
    if (columnIndex === 4 && rowIndex === 0) {
      // 取个超长 比所有商品长就行
      return [100, 1]
    } else if (columnIndex === 4 && rowIndex !== 0) {
      return [0, 0]
    }
  }
</script>
<style lang="scss" scoped>
  @import '@/styles/mixin.scss';

  .orderManage-container {
    margin: 22px;

    .tools-container {
      margin-bottom: 22px;

      span {
        margin-top: 5px;
        font-size: 12px;
        color: #606266;
      }
    }

    //.cell-img {
    //  display: flex;
    //  .imageView-container {
    //    width: 80px;
    //    height: 80px;
    //    border-radius: 5px;
    //  }
    //  span {
    //    margin-left: 8px;
    //    overflow: hidden;
    //    text-overflow: ellipsis;
    //    display: -webkit-box;
    //    -webkit-line-clamp: 3;
    //    -webkit-box-orient: vertical;
    //  }
    //}
    .selClass {
      margin-bottom: 10px;
      padding-left: 10px;
      display: flex;
      align-items: center;

      span {
        margin-left: 2px;
        margin-right: 10px;
      }
    }

    .header-container {
      @include card-shadow;
      padding: 12px;
      background-color: white;

      .el-form-item {
        margin-top: 15px;
        margin-bottom: 15px;
      }
    }

    .content-container {
      @include card-shadow;
      margin-top: 22px;
      background-color: white;
      padding: 11px;

      .section-header {
        display: flex;
        align-items: center;
        justify-content: space-between;

        :deep(.el-button) {
          padding-top: 0px;
          padding-bottom: 0px;
        }
      }

      // :deep(el-table__cell) {
      //   padding-top: 0px;
      //   padding-bottom: 0px;
      // }
      :deep(.el-radio-group) {
        margin-bottom: 10px !important;
      }

      .add-medicine {
        margin: 12px;
      }

      .cell-img {
        display: flex;

        .imageView-container {
          width: 80px;
          height: 80px;
          border-radius: 5px;
        }

        span {
          margin-left: 8px;
          font-size: 18px;
        }

        .tips {
          margin-left: 8px;
          font-size: 14px;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 1;
          -webkit-box-orient: vertical;
        }

        .tips + div {
          color: #909399;
        }
      }

      .shop-table-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
      }

      :deep(.el-table__expanded-cell) {
        padding-top: 0px !important;
      }
    }
  }
</style>
